package com.example.servlet;

import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.*;
import javax.servlet.annotation.*;

@WebServlet(name = "helloServlet", value = "/hello-servlet")
public class HelloServlet extends HttpServlet {

    /* 当前Servlet类对象的初始化方法：第一次被请求，创建对象，同时调用init方法 */
    @Override
    public void init() throws ServletException {
        System.out.println("hello-servlet初始化");
        super.init();
    }

    /* 去判断是否为http请求，是的话调用重载的service方法 */
    /* 每次请求都会调用这个方法 */
    @Override
    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        System.out.println("service1");
        super.service(req, res);
    }

    /* 根据method去分发到doGet/doPost... */
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("service2");
        System.out.println(req.getMethod()); // get/post
        super.service(req, resp);
    }

    /* tomcat服务停止时候，销毁该Servlet类的对象 */
    @Override
    public void destroy() {
        System.out.println("hello-servlet被销毁");
        super.destroy();
    }

    public void doGet(HttpServletRequest request,
                      HttpServletResponse response) throws IOException {
        /* 查一查这个控制台打印中文乱码的问题 */
        System.out.println("你好，servlet");
        response.setContentType("text/html");
        // Hello
        PrintWriter out = response.getWriter();
        try {
            System.out.println(5/0); // 报错
            out.println("<html><body>");
            out.println("<h1>Hello Servlet</h1>");
            out.println("</body></html>");
        } catch (Exception e) {
            out.println("error");
        }
    }
}